import re

from rest_framework import serializers

from user import models


def checkPhone(value):
    if not re.match(r'^1[34578]\d{9}$', value):
        raise serializers.ValidationError('手机号格式不正确')
    else:
        if models.User.objects.filter(phone=value):
            raise serializers.ValidationError('手机号已存在')


def checkEmail(value):
    if not re.match(r'^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$', value):
        raise serializers.ValidationError('邮箱格式不正确')
    else:
        if models.User.objects.filter(email=value):
            raise serializers.ValidationError('邮箱已存在')


def checkUserName(value):
    if not re.match(r'^[a-zA-Z0-9_-]{4,16}$', value):
        raise serializers.ValidationError('用户名格式不正确')
    else:
        if models.User.objects.filter(username=value):
            raise serializers.ValidationError('用户名已存在')


class UserRegisterSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = '__all__'
        extra_kwargs = {
            'username': {
                'validators': [checkUserName]
            },
            'email': {
                'validators': [checkEmail]
            },
            'phone': {
                'validators': [checkPhone]
            },
            'password': {}
        }


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.User
        fields = '__all__'
